import axios from 'axios'
import GlobalConstants from '../constants/Global.Constants'
import {Message} from 'element-ui'

// axios
axios.defaults.baseURL = GlobalConstants.BASE_URL
axios.defaults.withCredentials = true
//添加一个请求拦截器
axios.interceptors.request.use(function (config) {
  //在请求发出之前进行一些操作，比如请求头携带内容
  return config;
}, function (error) {
  //Do something with request error
  return error;
});

//添加一个响应拦截器
axios.interceptors.response.use(function (res) {
  // lsl 添加文件下载逻辑, 默认下载的status均为201
  if(res.status == 201) {
    return res.data;
  }

  if(!res.data.header) {
    console.log(res.data);
    Message({
      type: 'error',
      message: "响应数据格式有误！"
    });
  }
  // 登录超时或未登录， 重定向到登录界面
  if (res.data.header.returnCode == '990005') {
    window.location.href = '/';
    return false;
  }

  if (res.data.header.returnCode != '000000') {
    Message({
      type: 'error',
      message: res.data.header.returnMessage
    });
    return false;
  }
  return res.data;
}, function (error) {
  let errorMsg;
  if (error && error.response && error.response.status) {
    switch (error.response.status) {
      case 400:
        errorMsg = '请求错误'
        break
      case 401:
        errorMsg = '未授权，请登录'
        break
      case 403:
        errorMsg = '拒绝访问'
        break
      case 404:
        errorMsg = '未找到访问地址'
        break
      case 408:
        errorMsg = '请求超时'
        break
      case 500:
        errorMsg = '服务器内部错误'
        break
      case 501:
        errorMsg = '服务未实现'
        break
      case 502:
        errorMsg = '网关错误'
        break
      case 503:
        errorMsg = '服务不可用'
        break
      case 504:
        errorMsg = '网关超时'
        break
      case 505:
        errorMsg = 'HTTP版本不受支持'
        break
      default:
    }
  }

  console.log('请求失败：' + errorMsg)

  //Do something with response error
  return error;
})


export default axios